package com.caijin.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caijin.common.core.domain.Result;
import com.caijin.common.core.domain.entity.Catalogue;
import com.caijin.common.core.domain.entity.Comment;
import com.caijin.common.core.domain.vo.CatalogueVO;
import com.caijin.common.core.domain.vo.CommentVO;
import com.caijin.common.util.ListToTree;
import com.caijin.system.mapper.CatalogueMapper;
import com.caijin.system.mapper.CommentMapper;
import com.caijin.system.mapper.StudentMapper;
import com.caijin.system.service.ICatalogueService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程目录表 服务实现类
 * </p>
 *
 * @author Peas
 * @since 2021-01-31
 */
@Service
public class CatalogueServiceImpl extends ServiceImpl<CatalogueMapper, Catalogue> implements ICatalogueService {

    @Autowired
    private CatalogueMapper mapper;

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private StudentMapper studentMapper;

    /**
     * 获取章节目录
     *
     * @param cno 课程id
     * @return 章节目录
     */
    @Override
    public Result getChapterList(Long cno) {
        return ListToTree.catalogueToTreeForList(mapper.getCatalogueList(cno));
    }

    @Override
    public Result getChapterById(Long id) {
        Map<String, Object> dataReturn = new HashMap<>();

        Catalogue catalogue = mapper.selectById(id);

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("catalogue_id", id);

        List<Comment> list = commentMapper.selectList(queryWrapper);
        List<CommentVO> commentVOS = ListToTree.commentListToTree(list);

        dataReturn.put("catalogue", catalogue);
        dataReturn.put("commentList", commentVOS);

        return Result.ok().data("map", dataReturn);
    }

    /**
     * 删除某一章节
     *
     * @param id 章节id
     * @return 结果
     */
    @Override
    public Result deleteChapter(Long id, Long cno) {
        QueryWrapper<Catalogue> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cno", cno);
        List<Catalogue> catalogues = this.mapper.selectList(queryWrapper);
        List<CatalogueVO> data1 = ListToTree.catalogueToFree(catalogues, id);
        CatalogueVO catalogueVO2 = data1.get(0);
        deleteChildren(catalogueVO2);
        return Result.ok().message("删除章节成功");
    }

    /**
     * 删除树节点和它的所有子结点
     *
     * @param catalogueVO 树的根节点
     */
    private void deleteChildren(CatalogueVO catalogueVO) {
        if (catalogueVO.getChildren() != null) {
            for (CatalogueVO catalogueVO1 : catalogueVO.getChildren()) {
                deleteChildren(catalogueVO1);
            }
        }
        this.mapper.deleteById(catalogueVO.getId());
    }

}
